const Koa = require('koa')
const Router = require('@koa/router')
const cors = require('koa2-cors')
const { PrismaClient } = require('@prisma/client')
require('dotenv').config()
const habitRouter = require('./habit')
const path = require('path');
const { uploadFileBuffer } = require('../utils/minio-client');
const app = new Koa()
const router = new Router()
const prisma = new PrismaClient()
const { exec } = require('child_process');
const { koaBody } = require('koa-body');
const fs = require('fs');

app.use(koaBody({
  multipart: true,
  formidable: {
    maxFileSize: 100 * 1024 * 1024, // 最大100MB
    keepExtensions: true // 保留文件扩展名
  }
}))

// 服务端支持跨域
app.use(cors({
  origin: function (ctx) {
    const requestOrigin = ctx.get('Origin');
    const whiteList = ['https://app.insist.life','https://habit.insist.life', 'http://localhost:5173']
    if (whiteList.includes(requestOrigin)) {
      return requestOrigin;
    }
    return false;
  },
  credentials: true // 允许跨域的时候带着 cookie
}))

router.get('/users', async (ctx) => {
  const users = await prisma.users.findMany()
  ctx.body = users
})

router.post('/webhook', async (ctx) => {
  ctx.body = { success: true, message: '部署已开始' };
  setTimeout(() => {
    exec('/var/www/habit-koa/deploy.sh', (error, stdout, stderr) => {
      if (error) {
        console.error('❌ 部署失败:', error.message);
        console.error(stderr);
      } else {
        console.log('✅ 部署成功:\n', stdout);
      }
    });
  }, 1000);
});

router.post('/upload', async (ctx) => {
  // 从请求中获取文件
  const file = ctx.request.files?.file
  
  if (!file) {
    ctx.status = 400
    ctx.body = { error: 'No file uploaded' }
    return
  }

// 处理不同格式的文件对象（兼容不同版本的koa-body）
    let filePath, originalName, mimeType
    
    if (file.filepath) { // 新版本koa-body格式
      filePath = file.filepath
      originalName = file.originalFilename
      mimeType = file.mimetype
    } else if (file.path) { // 旧版本格式
      filePath = file.path
      originalName = file.name
      mimeType = file.type
    } else {
      throw new Error('Unsupported file object format')
    }

  try {
    // 读取上传的文件
    const fileBuffer = await fs.promises.readFile(filePath)
    
    // 生成唯一的文件名
    const ext = path.extname(originalName)
    const fileName = `${Date.now()}${ext}`
    
    // 上传到MinIO
    const fileUrl = await uploadFileBuffer(fileName, fileBuffer, {
      'Content-Type': mimeType,
      'Original-Filename': originalName
    })
    
    ctx.body = {
      success: true,
      url: fileUrl,
      fileName: fileName,
      originalName: originalName
    }
  } catch (error) {
    console.error('Upload error:', error)
    ctx.status = 500
    ctx.body = { error: 'File upload failed', details: error.message }
  }
})


app.use(router.routes()).use(router.allowedMethods())
app.use(habitRouter.routes()).use(habitRouter.allowedMethods())

app.listen(9000, () => console.log(`🚀 http://localhost:9000`))
